import React, { PureComponent } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  FlatList,
  TouchableOpacity,
} from 'react-native';

export default class RepositoryCell extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isFavorite: this.props.projectModel.isFavorite,
      favoriteIcon: this.props.projectModel.isFavorite ? require('../../res/images/ic_star.png') : require('../../res/images/ic_unstar_transparent.png'),
    }
  }


  setFavoriteState(isFavorite) {
    this.setState({
      isFavorite: isFavorite,
      favoriteIcon: isFavorite ? require('../../res/images/ic_star.png') : require('../../res/images/ic_unstar_transparent.png')
    })
  }

  // 当用户点击时返回告诉父组件,让父组件处理
  onPressFavorite() {
    this.setFavoriteState(!this.state.isFavorite)
    this.props.onFavorite(this.props.projectModel.item, !this.state.isFavorite);
  }

  // 在组件接收到一个新的prop时被执行
  componentWillReceiveProps(nextProps) {
    this.setFavoriteState(nextProps.projectModel.isFavorite);
  }

  render() {
    let item = this.props.projectModel.item ? this.props.projectModel.item : this.props.projectModel;
    let favoriteButton = <TouchableOpacity
      style={{ padding: 6 }}
      onPress={() => this.onPressFavorite()} underlayColor='transparent'>
      <Image
        ref='favoriteIcon'
        style={[{ width: 22, height: 22, }, { tintColor: "#2196F3" }]}
        source={this.state.favoriteIcon} />
    </TouchableOpacity>;
    return <TouchableOpacity onPress={this.props.onSelect}>
      <View style={styles.cell_container}>
        <Text style={styles.title}>{item.full_name}</Text>
        <Text style={styles.description}>{item.description}</Text>
        {/* 横排 */}
        <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text>Author: </Text>
            <Image
              style={{ height: 22, width: 22 }}
              source={{ uri: item.owner.avatar_url }}
            />
          </View>
          <View style={{ flexDirection: 'row', alignItems: 'center', }}>
            <Text>Starts: </Text>
            <Text>{item.stargazers_count}</Text>
          </View>
          {favoriteButton}
        </View>
      </View>
    </TouchableOpacity>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  title: {
    fontSize: 16,
    marginBottom: 2,
    color: '#212121'
  },
  description: {
    fontSize: 14,
    marginBottom: 2,
    color: '#757575',
    borderRadius: 2,
  },
  cell_container: {
    backgroundColor: 'white',
    borderColor: '#dddddd',
    padding: 10,
    marginLeft: 5,
    marginRight: 5,
    marginVertical: 3,
    borderWidth: 0.5,
    shadowColor: 'gray',
    // IOS
    shadowOffset: { width: 0.5, height: 0.5 },
    shadowOpacity: 0.4,
    shadowRadius: 1,
    // Android 阴影
    elevation: 2,
  }
})